import {
  Button,
  Form,
  Input,
  Checkbox,
  message,
  Tabs,
  Row,
  Col,
  Drawer,
  Divider,
  Spin,
} from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import React, { useState, useRef } from "react";
import to from "await-to-js";
import {
  login as loginApi,
  getEmailCode as getEmailCodeApi,
  emailLogin as emailLoginApi,
  register as registerApi,
} from "@/api/login";
import { useNavigate } from "react-router-dom";
import { customEmailRule, customPasswordRule } from "@/utils/validate";
import { getUserInfo } from "@/store/features/user";
import { useDispatch } from "react-redux";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
type MyFunctionType = (arg: boolean) => void;
// 登录框
const Login: React.FC = (props) => {
  // 登录表单数据
  const loginForm = useRef({
    username: "",
    password: "",
  });
  // 邮箱登录参数
  const emailParams = useRef({
    email: "",
    emailCode: "",
  });
  // loading状态
  const [spinning, setSpinning] = React.useState<boolean>(false);

  const [messageApi, contextHolder] = message.useMessage();
  // 密码手机号登录
  const [isPassWord, setIsPassWord] = useState(true);
  // 注册抽屉
  const [openDrawer, setOpenDrawer] = useState(false);
  // 控制验证码是否禁用
  const [disabled, setDisabled] = useState(false);
  const registerParams = useRef({
    username: "",
    password: "",
    email: "",
    emailCode: "",
    businessType: "email_type_register",
  });
  // 路由跳转
  const navigateTo = useNavigate();
  const dispatch = useDispatch();
  const loginBoxContent = [
    {
      key: "1",
      label: <div>账号密码登录</div>,
    },
    {
      key: "2",
      label: <div>邮箱登录</div>,
    },
  ];
  // 密码登录按钮
  const onFinish = async (values: { password: string; username: string }) => {
    // 获取表单数据
    setSpinning(true);
    console.log(values);
    loginForm.current.password = values.password;
    loginForm.current.username = values.username;
    const [err, res] = await to(loginApi(loginForm.current));
    if (!err) {
      // 登录成功
      messageApi.open({
        type: "success",
        content: "登录成功",
      });
      (props as { changeLoginStatus: MyFunctionType }).changeLoginStatus(true);
      // 本地保存token
      // localStorage.setItem("token", res.data.token);
      // 全局跟本地保存用户信息
      dispatch(getUserInfo(res.data.token));
      setSpinning(false);
    }
  };
  /**
   * 邮箱登录按钮
   * @values 参数
   */
  const handleEmailLogin = async (values: {
    email: string;
    emailCode: string;
  }) => {
    setSpinning(true);
    emailParams.current.email = values.email;
    emailParams.current.emailCode = values.emailCode;
    const [err, res] = await to(emailLoginApi(emailParams.current));
    if (!err) {
      console.log(res);
      messageApi.open({
        type: "success",
        content: "登录成功",
      });
      (props as { changeLoginStatus: MyFunctionType }).changeLoginStatus(true);
      // 拿到并保存token
      // localStorage.setItem("token", res.data.token);
      // 全局保存用户信息
      dispatch(getUserInfo(res.data.token));
      setSpinning(false);
    } else {
      messageApi.open({
        type: "error",
        content: "登录失败",
      });
      setSpinning(false);
    }
  };

  /**
   * tab切换
   * @param key tab key
   */
  const onTabClick = (key: string) => {
    if (key === "1") {
      // 密码登录
      setIsPassWord(true);
    } else {
      // 邮箱登录
      setIsPassWord(false);
    }
  };
  // 注册按钮
  const handleRegister = () => {
    setOpenDrawer(true);
  };
  // 关闭侧抽屉
  const onClose = () => {
    setOpenDrawer(false);
  };
  /**
   * 忘记密码按钮
   */
  const handleForgetPassword = () => {
    navigateTo("/find");
  };

  const [timer, setTimer] = useState(10);
  /**
   * 获取验证码
   */
  const handleGetEmailCode = async (email: string) => {
    setSpinning(true);
    console.log(email);
    const currentParams = {
      email: email,
    };
    const [err, res] = await to(getEmailCodeApi(currentParams));
    if (!err) {
      console.log(res);
      // 发送成功设置定时器
      setDisabled(true);
      setSpinning(false);
      // 自定义定时器
      const intervalID = setInterval(() => {
        setTimer((timer) => {
          if (timer === 0) {
            // 当时间到达0时，清除定时器并退出
            clearInterval(intervalID);
            setDisabled(false);
            return 10;
          }
          timer = timer - 1;
          console.log(timer);
          return timer;
        });
      }, 1000);
    } else {
      message.error("获取验证码失败");
      setSpinning(false);
    }
  };

  /**
   * 注册按钮
   */
  const handleRegisterSubmit = async () => {
    setSpinning(true);

    console.log(registerParams.current);
    const [err] = await to(registerApi(registerParams.current));
    if (!err) {
      message.success("注册成功，请登录！");
      setOpenDrawer(false);
      setSpinning(false);
    } else {
      message.error("注册失败");
      setSpinning(false);
    }
  };
  return (
    <>
      <Spin tip="Loading" size="large" spinning={spinning}>
        {contextHolder}
        <Tabs
          defaultActiveKey="1"
          centered
          onTabClick={onTabClick}
          items={loginBoxContent.map(
            (item: { key: string; label: JSX.Element }) => {
              return {
                label: item.label,
                key: item.key,
              };
            }
          )}
        />
        {isPassWord ? (
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{ remember: false }}
            onFinish={onFinish}
          >
            <div className="flex">
              <div className="w60% mt-4">
                <Form.Item
                  name="username"
                  rules={[
                    {
                      required: true,
                      message: "请输入账号!",
                    },
                  ]}
                >
                  <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    placeholder="用户名"
                  />
                </Form.Item>

                <Form.Item
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: "请输入密码!",
                    },
                    { validator: customPasswordRule },
                  ]}
                >
                  <Input
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    type="password"
                    placeholder="密码"
                  />
                </Form.Item>
                <Form.Item>
                  <Form.Item name="remember" valuePropName="checked" noStyle>
                    <Checkbox>记住密码</Checkbox>
                  </Form.Item>
                  <Button
                    type="link"
                    className="login-form-button"
                    style={{ color: "rgba(94, 175, 143)" }}
                    onClick={handleForgetPassword}
                  >
                    忘记密码
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    className="login-form-button w45%"
                    onClick={handleRegister}
                  >
                    注册
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="login-form-button w45% ml-6"
                  >
                    登录
                  </Button>
                </Form.Item>
              </div>
              <div className="w180px h180px mt-4 ml-5">
                <img className="w100% h100%" src={"logo.jpg"} />
              </div>
            </div>
          </Form>
        ) : (
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{ remember: false }}
            onFinish={handleEmailLogin}
          >
            <Form.Item
              name="email"
              rules={[
                {
                  required: true,
                  message: "请输入邮箱!",
                },
                { validator: customEmailRule },
              ]}
            >
              <Row gutter={16}>
                <Col span={18}>
                  <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    placeholder="邮箱"
                    onChange={(e) => {
                      emailParams.current.email = e.target.value;
                    }}
                  />
                </Col>
                <Divider
                  className="h8"
                  style={{ color: "#333", marginLeft: "10px" }}
                  type="vertical"
                />
                <Col span={3} className="flex">
                  <Button
                    disabled={disabled}
                    style={
                      disabled
                        ? { marginLeft: "-20px" }
                        : { marginLeft: "-20px", color: "rgba(94, 175, 143)" }
                    }
                    type="link"
                    size={"middle"}
                    onClick={() => {
                      handleGetEmailCode(emailParams.current.email);
                    }}
                  >
                    获取验证码
                    {disabled && <span>{timer}s</span>}
                  </Button>
                </Col>
              </Row>
            </Form.Item>
            <Form.Item
              name="emailCode"
              rules={[
                {
                  required: true,
                  message: "请输入验证码!",
                },
              ]}
            >
              <Row gutter={16}>
                <Col span={18}>
                  <Input
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    placeholder="验证码"
                  />
                </Col>
              </Row>
            </Form.Item>
            <Form.Item>
              <div>
                {/* 没有密码？ <a href="">立即注册!</a> */}
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-form-button w88"
                >
                  登录
                </Button>
              </div>
            </Form.Item>
          </Form>
        )}
        <Drawer
          title="用户注册"
          placement="right"
          size="large"
          onClose={onClose}
          open={openDrawer}
        >
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            onFinish={handleRegisterSubmit}
            autoComplete="off"
          >
            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                {
                  required: true,
                  message: "请输入邮箱!",
                },
                { validator: customEmailRule },
              ]}
            >
              <Row gutter={16}>
                <Col span={18}>
                  <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    placeholder="邮箱"
                    onChange={(e) => {
                      registerParams.current.email = e.target.value;
                    }}
                  />
                </Col>
                <Divider
                  className="h8"
                  style={{ color: "#333", marginLeft: "10px" }}
                  type="vertical"
                />
                <Col span={3} className="flex">
                  <Button
                    disabled={disabled}
                    style={
                      disabled
                        ? { marginLeft: "-20px" }
                        : { marginLeft: "-20px", color: "rgba(94, 175, 143)" }
                    }
                    type="link"
                    size={"middle"}
                    onClick={() =>
                      handleGetEmailCode(registerParams.current.email)
                    }
                  >
                    获取验证码
                    {disabled && <span>{timer}s</span>}
                  </Button>
                </Col>
              </Row>
            </Form.Item>
            <Form.Item
              label="验证码"
              name="emailCode"
              rules={[
                {
                  required: true,
                  message: "请输入验证码!",
                },
              ]}
            >
              <Row gutter={16}>
                <Col span={18}>
                  <Input
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    placeholder="验证码"
                    onChange={(e) => {
                      registerParams.current.emailCode = e.target.value;
                    }}
                  />
                </Col>
              </Row>
            </Form.Item>
            <Form.Item<FieldType>
              label="用户名"
              name="username"
              rules={[
                {
                  required: true,
                  message: "请输入账号!",
                },
              ]}
            >
              <Input
                onChange={(e) => {
                  registerParams.current.username = e.target.value;
                }}
              />
            </Form.Item>

            <Form.Item<FieldType>
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: "请输入密码!",
                },
              ]}
            >
              <Input.Password
                onChange={(e) => {
                  registerParams.current.password = e.target.value;
                }}
              />
            </Form.Item>

            {/* <Form.Item<FieldType>
            label="再次输入密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码!",
              },
            ]}
          >
            <Input.Password
              onChange={(e) => {
                registerParams.current.password = e.target.value;
              }}
            />
          </Form.Item> */}

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确定注册
              </Button>
            </Form.Item>
          </Form>
        </Drawer>
      </Spin>
    </>
  );
};

export default Login;
